package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author Tang
 * @classname Client
 * @description [  ]
 * @date 2021/2/22 21:31
 */
public class Client {

    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9000));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        SelectionKey register = socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        new Thread(() -> {
            while (true) {
                try {
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        if (selectionKey.isConnectable()) {
                            if (channel.finishConnect()) {
                                System.out.println("OP_CONNECT....finish...");
                                selectionKey.interestOps(SelectionKey.OP_READ);
                            }else {
                                System.out.println("OP_CONNECT....fail...");
                            }
                        } else if (selectionKey.isReadable()) {
                            System.out.println("OP_READ....");
                            byte[] bt = new byte[1024];
                            while (byteBuffer.hasRemaining()) {
                                channel.read(byteBuffer);
                                byteBuffer.flip();
                                System.out.println(byteBuffer.position() + "--->" + byteBuffer.limit());
                                byteBuffer.get(bt,0,byteBuffer.limit());
                                System.out.println("接收到的msg:"+new String(bt));
                            }
                        }
                        iterator.remove();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            try {
                socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}